import Vuex from 'vuex'
import Vue from 'vue'
import { info } from '../api/oper.js'
import router from '../router'

// 使用安装
Vue.use(Vuex)

export default new Vuex.Store({
  state() {
    return {
      userinfo: {},
      token: ''
    }
  },
  getters: {
    userinfo: (state) => {
      return state.userinfo
    },
    token: (state) => {
      return state.token
    }
  },
  mutations: {
    setUserinfo(state, userinfo) {
      state.userinfo = userinfo
    },
    setToken(state, token) {
      state.token = token
    }
  },
  actions: {
    getUserinfo(context) {
      return new Promise((resolve, reject) => {
        info()
        .then((res) => {
          context.commit('setUserinfo', { ...res.data.data })
          resolve([null, res.data.data])
        })
        .catch((e) => {
          localStorage.removeItem('token')
          router.replace('/login')
          reject(e, null)
        })
      }).catch(err => err)
    }
  }
})
